//
//  connectRobotWifiVController.m
//  SKaURobot
//
//  Created by cdong on 16/2/24.
//  Copyright © 2016年 cdong. All rights reserved.
//

#import "connectRobotWifiVController.h"
#import "connectRobotWifi.h"
#import <SystemConfiguration/CaptiveNetwork.h>
#import "connectRobotWifiTVCell.h"
#import "connectCreateWifiVController.h"
#import "isConnectNet.h"
#import "SKFirstVController.h"

@interface connectRobotWifiVController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic ,strong)connectRobotWifi *connectRobotV;
@property (nonatomic ,assign)NSInteger pwdShiftFlag;
@property (nonatomic ,assign)NSInteger wifiShiftFlag;
@property (nonatomic ,strong)UITableView *downListTV;
@property (nonatomic ,strong)NSMutableArray *wifiMutableArr;
@property (nonatomic ,assign)BOOL flagEnble;

@end

@implementation connectRobotWifiVController

- (void)loadView{
    self.connectRobotV = [[connectRobotWifi alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
    self.view = self.connectRobotV;
}

- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

// 返回
- (void)backBtnAction:(UIButton *)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

// 切换密文／明文Next
- (void)pwdShiftBtnActionNext:(UIButton *)sender{
    if (self.pwdShiftFlag == 1) {
        self.connectRobotV.pawTF.secureTextEntry = YES;
        [self.connectRobotV.pawBtn setBackgroundImage:[UIImage imageNamed:@"icon_eye"] forState:UIControlStateNormal];
        self.pwdShiftFlag = 0;
    }else{
        self.connectRobotV.pawTF.secureTextEntry = NO;
        [self.connectRobotV.pawBtn setBackgroundImage:[UIImage imageNamed:@"icon_eye_red"] forState:UIControlStateNormal];
        self.pwdShiftFlag = 1;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = YES;
    self.pwdShiftFlag = 0;
    self.wifiShiftFlag = 1;
    self.flagEnble = NO;
    
    [self.connectRobotV.createQRCodeBtn addTarget:self action:@selector(createQRCodeBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.connectRobotV.pawBtn addTarget:self action:@selector(pwdShiftBtnActionNext:) forControlEvents:UIControlEventTouchUpInside];
    [self.connectRobotV.backBtn addTarget:self action:@selector(backBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.connectRobotV.wifiNameBtn addTarget:self action:@selector(wifiNameBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldChanged) name:UITextFieldTextDidChangeNotification object:self.connectRobotV.pawTF];
}

static BOOL flagFirst = NO;

#warning 测试
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (!isConnectionAvailable()) {
        self.connectRobotV.wifiNameTF.text = @"未连接wifi";
        self.flagEnble = NO;
    }else{
        self.flagEnble = YES;
        if (!flagFirst) {
            self.connectRobotV.wifiNameTF.text = @"未连接wifi";
        }else{
            self.wifiMutableArr = [self getWifiSSID];
            if (self.wifiMutableArr.count > 0) {
                self.connectRobotV.wifiNameTF.text = self.wifiMutableArr[0];
                self.downListTV = [[UITableView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.connectRobotV.wifiNameTF.frame), self.view.frame.size.width, 45*self.wifiMutableArr.count) style:(UITableViewStylePlain)];
                [self.downListTV registerNib:[UINib nibWithNibName:@"connectRobotWifiTVCell" bundle:nil] forCellReuseIdentifier:@"connectRobotWifiTVCell"];
                self.downListTV.delegate = self;
                self.downListTV.dataSource = self;
            }else{
                self.connectRobotV.wifiNameTF.text = @"未连接wifi";
            }
        }
    }
}

/*
 - (void)wifiUpdate{
 if (!isConnectionAvailable()) {
 self.connectRobotV.wifiNameTF.text = @"未连接wifi";
 self.flagEnble = NO;
 }else{
 self.flagEnble = YES;
 if (!flagFirst) {
 self.connectRobotV.wifiNameTF.text = @"未连接wifi";
 }else{
 self.wifiMutableArr = [self getWifiSSID];
 if (self.wifiMutableArr.count > 0) {
 self.connectRobotV.wifiNameTF.text = self.wifiMutableArr[0];
 self.downListTV = [[UITableView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.connectRobotV.wifiNameTF.frame), self.view.frame.size.width, 45*self.wifiMutableArr.count) style:(UITableViewStylePlain)];
 [self.downListTV registerNib:[UINib nibWithNibName:@"connectRobotWifiTVCell" bundle:nil] forCellReuseIdentifier:@"connectRobotWifiTVCell"];
 self.downListTV.delegate = self;
 self.downListTV.dataSource = self;
 }else{
 self.connectRobotV.wifiNameTF.text = @"未连接wifi";
 }
 }
 }
 }
*/

// 获取周围Wi-Fi的SSID
- (NSMutableArray *)getWifiSSID{
    NSMutableArray *wifiArray = [[NSMutableArray alloc]init];
    // 获取Wi-Fi
    NSArray *ifs = (__bridge_transfer id)CNCopySupportedInterfaces();
    NSLog(@"Supported interfaces: %@", ifs);
    id info = nil;
    for (NSString *ifnam in ifs) {
        info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
        [wifiArray addObject:info[@"SSID"]];
        NSLog(@"%@ => %@", ifnam, info);  //单个数据info[@"SSID"]; info[@"BSSID"];
        if (info && [info count]) { break; }
    }
    return wifiArray;
}

/*
 for(NEHotspotNetwork *hotspotNetwork in [NEHotspotHelper supportedNetworkInterfaces]) {
 NSString *ssid = hotspotNetwork.SSID;
 NSString *bssid = hotspotNetwork.BSSID;
 BOOL secure = hotspotNetwork.secure;
 BOOL autoJoined = hotspotNetwork.autoJoined;
 double signalStrength = hotspotNetwork.signalStrength;
 }
 */

// 选择Wi-Fi
- (void)wifiNameBtnAction:(UIButton *)sender{
    flagFirst = YES;
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=WIFI"]];
//    if (self.wifiShiftFlag == 1) {
//        [self.view addSubview:self.downListTV];
//        self.wifiShiftFlag = 0;
//    }else{
//        [self.downListTV removeFromSuperview];
//        self.wifiShiftFlag = 1;
//    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.wifiMutableArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    connectRobotWifiTVCell *cell = [tableView dequeueReusableCellWithIdentifier:@"connectRobotWifiTVCell" forIndexPath:indexPath];
    cell.wifiNameL.text = self.wifiMutableArr[indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 45.0f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSUserDefaults *dd = [NSUserDefaults standardUserDefaults];
    self.connectRobotV.wifiNameTF.text = self.wifiMutableArr[indexPath.row];
    [dd setObject:self.connectRobotV.wifiNameTF.text forKey:@"CurrentWifiName"];
    if (self.wifiShiftFlag == 0) {
        [self.downListTV removeFromSuperview];
        self.wifiShiftFlag = 1;
    }
}

// 生成二维码按钮
- (void)createQRCodeBtnAction:(UIButton *)sender{
    NSUserDefaults *dd = [NSUserDefaults standardUserDefaults];
    [dd setObject:self.connectRobotV.pawTF.text forKey:@"CurrentWifiPwd"];
    connectCreateWifiVController *creatVC = [[connectCreateWifiVController alloc]init];
    [self.navigationController pushViewController:creatVC animated:YES];
}

// 输入框文字判断
- (void)textFieldChanged{
    if (![self.connectRobotV.pawTF.text isEqualToString:@""] && self.flagEnble == YES) {
        self.connectRobotV.createQRCodeBtn.userInteractionEnabled = YES;
        [self.connectRobotV.createQRCodeBtn setTitleColor:[RGBColorEncapsulation colorWithRGB:0xffffff alpha:1] forState:UIControlStateNormal];
    }else{
        self.connectRobotV.createQRCodeBtn.userInteractionEnabled = NO;
        [self.connectRobotV.createQRCodeBtn  setTitleColor:[RGBColorEncapsulation colorWithRGB:0xffffff alpha:.5] forState:UIControlStateNormal];
    }
}

// 点击return回收键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

// 点击空白回收键盘
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.connectRobotV.wifiNameTF resignFirstResponder];
    [self.connectRobotV.pawTF resignFirstResponder];
    if (self.wifiShiftFlag == 0) {
        [self.downListTV removeFromSuperview];
        self.wifiShiftFlag = 1;
    }
}

- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
